package problem25;

//25.k个一组翻转链表
//https://leetcode.cn/problems/reverse-nodes-in-k-group/

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode reverseKGroup(ListNode head, int k) {
        ListNode newHead = new ListNode();
        ListNode curA = newHead, curB = head;
        while(curB != null) {
            //让curB向前走k步
            ListNode begin = curB;
            int count = 0;
            for(; count<k && curB != null; count++) {
                curB = curB.next;
            }
            // 如果是最后一部分不足k个节点, 不逆序
            if(count < k) {
                curA.next = begin;
                break;
            }
            //翻转链表
            while(begin != curB) {
                ListNode next = begin.next;
                begin.next = curA.next;
                curA.next = begin;
                begin = next;
            }

            for(int i = 0; i<k; i++) {
                curA = curA.next;
            }
        }
        return newHead.next;
    }
}